import { listTopInvokeInterfaceInfoUsingGet } from '@/services/openAPI-backend/analysisController';
import {
  BarChartOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Tabs} from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';
import {dateStatisticsByWeekUsingGet} from "@/services/openAPI-backend/dateStatisticsController";
import {keyframes} from "antd-style";
const Admin: React.FC = () => {
  const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateY(100%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateY(0); /* 结束位置在正常位置 */
        }
`;
  const [data, setData] = useState<API.InterfaceInfoVO[]>([]);
  const [loading, setLoading] = useState(true);
  const [weekdata, setWeekData] = useState<any>([]);
  const [wenxinData, setWenxinData] = useState<number>([]);
  const [userNameData, setuserNameData] = useState<number>([]);
  const [tongyiData, settongyiData] = useState<number>([]);
  const [ipData, setipData] = useState<number>([]);
  const [weatherData, setweatherData] = useState<number>([]);
  const [soundData, setSoundData] = useState<number>([]);
  const [translationData, setTranslationData] = useState<number>([]);
  const [ptotData, setptotData] = useState<number>([]);
  const [ttopData, settopData] = useState<number>([]);
  function getRecentwWeekDates() {
    // 获取当前日期的副本，用于后续操作
    let currentDate = new Date();
    // 初始化日期数组
    let datesArray = [];
    let tempDate = new Date();
    // 循环七次，包括今天和之前的六天
    for (let i = 0; i <= 6; i++) {
      // 将当前日期减去i天
      if(currentDate.getDate()<=i){
        tempDate.setMonth(currentDate.getMonth() - 1);
        if(currentDate.getMonth()-1===1&currentDate.getMonth()-1===3&currentDate.getMonth()-1===5&currentDate.getMonth()-1===7&currentDate.getMonth()-1===8&currentDate.getMonth()-1===10&currentDate.getMonth()-1===12)
          tempDate.setDate(31-i+currentDate.getDate());
        else
          tempDate.setDate(30-i+currentDate.getDate());
      }else {
        tempDate.setDate(currentDate.getDate() - i);
      }
      // 获取年月日并格式化
      let year = tempDate.getFullYear();
      let month = ('0' + (tempDate.getMonth() + 1)).slice(-2); // 月份需要加1并格式化
      let day = ('0' + tempDate.getDate()).slice(-2); // 日期也需要格式化
      // 将格式化后的日期添加到数组中
      datesArray.push(`${year}-${month}-${day}`);
      console.log(`${year}-${month}-${day}`);
      if(currentDate.getDate()<=i){
        tempDate.setMonth(currentDate.getMonth() + 1);
      }
    }
    return datesArray;
  }
  let tempYearDay = getRecentwWeekDates();
  function getLineData(name:string,data:Map){
    const tempDATA = new Map(data);
    let dataArray = []
    for(let i = 0; i < tempYearDay.length; i++){
      let temp = tempDATA.get(tempYearDay[i])
      for(let j = 0; j < temp?.length; j++){
        if(temp[j].interfaceInfoName===name){
          dataArray.push(temp[j].invokeNum)
        }
      }
    }
    return dataArray;
  }
  function getRecentWeekDates() {
    let currentDate = new Date();
    let monthDaysArray = [];
    let tempDate = new Date();
    for (let i = 0; i <= 6; i++) {
      if(currentDate.getDate()<=i){
        tempDate.setMonth(currentDate.getMonth() - 1);
        if(currentDate.getMonth()-1===1&currentDate.getMonth()-1===3&currentDate.getMonth()-1===5&currentDate.getMonth()-1===7&currentDate.getMonth()-1===8&currentDate.getMonth()-1===10&currentDate.getMonth()-1===12)
        tempDate.setDate(31-i+currentDate.getDate());
        else
          tempDate.setDate(30-i+currentDate.getDate());
      }else {
        tempDate.setDate(currentDate.getDate() - i);
      }
      let month = ('0' + (tempDate.getMonth() + 1)).slice(-2);
      let day = ('0' + tempDate.getDate()).slice(-2);
      // 直接拼接月份和日期，不包含年份
      monthDaysArray.push(`${month}-${day}`);
      if(currentDate.getDate()<=i){
        tempDate.setMonth(currentDate.getMonth() + 1);
      }
    }

    return monthDaysArray;
  }
  const dataDate = getRecentWeekDates();
  function jsonToMap(jsonObj) {
    return new Map(Object.entries(jsonObj));
  }
  useEffect(() => {
    // 这里的逻辑只会在weekdata变化时执行
    if (weekdata) {
      setWenxinData(getLineData("千帆人工智能", weekdata));
      setptotData(getLineData("PictureToText", weekdata));
      settongyiData(getLineData("Dashscope", weekdata));
      setuserNameData(getLineData("医疗助手", weekdata));
      setipData(getLineData("ipLocation", weekdata));
      setweatherData(getLineData("天气助手", weekdata));
      settopData(getLineData("TextToPicture", weekdata));
      setTranslationData(getLineData('翻译',weekdata));
      setSoundData(getLineData("智慧语音",weekdata));
    }
  }, [weekdata]); // 添加weekData作为依赖项
  useEffect(() => {
    async function fetchData() {
      try {
        const res = await dateStatisticsByWeekUsingGet();
        if (res.data) {
          setWeekData(jsonToMap(res.data));
        }
        const resTop = await listTopInvokeInterfaceInfoUsingGet();
        if (resTop.data) {
          setData(resTop.data);
        }
      } catch (e) {
        // 可以在这里处理错误，比如记录日志
        console.error(e);
      }
    }

    fetchData(); // 只在组件挂载时执行
  }, []); // 保持依赖数组为空
  const chartData = Array.from(data).map((item) => {

    return {
      value: item.totalNum,
      name: item.name,
    };
  });
  const WeekColoption = {

    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },label: {
        backgroundColor: '#6a7985'
      }
    },
    legend: {
      data: ['医疗助手', 'Dashscope', '千帆人工智能', 'weather', 'ipLocation','texttopicture','weather-assiant','picturetotext','翻译',"智慧语音"],
      textStyle: { // 调整图例文字大小
        fontSize: 14,
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: dataDate,
        axisLabel: { // 调整y轴标签字体大小
          fontSize: 14,
        },
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: { // 调整y轴标签字体大小
          fontSize: 14,
        },
      }
    ],
    series: [
      {
        name: '医疗助手',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: userNameData
      },
 {
        name: 'weather-assiant',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: weatherData
      },
      {
        name: '千帆人工智能',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: wenxinData
      },
      {
        name: 'Dashscope',
        type: 'bar',
        barWidth: 25,
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: tongyiData
      },
      {
        name: '天气助手',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: weatherData
      },
      {
        name: '智慧语音',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: soundData
      },
      {
        name: '翻译',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: translationData
      },
      {
        name: 'ipLocation',
        type: 'bar',
        data: ipData,
        emphasis: {
          focus: 'series'
        },
     
      },
      {
        name: 'picturetotext',
        type: 'bar',
        barWidth: 5,
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: ptotData
      },
      {
        name: 'texttopicture',
        type: 'bar',
        stack: 'Total',
        emphasis: {
          focus: 'series'
        },
        data: ttopData,
      },
    ]
  };
  const Weekoption = {
    title: {
      text: '上周接口调用情况'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
       data: ['医疗助手', 'Dashscope', '千帆人工智能', 'weather', 'ipLocation','texttopicture','weather-assiant','picturetotext','翻译',"智慧语音"],
   textStyle: { // 调整图例文字大小
        fontSize: 14,
      },
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: dataDate,
        axisLabel: { // 调整x轴标签字体大小
          fontSize: 14,
        },
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: { // 调整y轴标签字体大小
          fontSize: 14,
        },
      }
    ],
    series: [
      {
        name: '医疗助手',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: userNameData
      },
      {
        name: 'Dashscope',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: tongyiData
      },
      {
        name: '千帆人工智能',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: wenxinData
      },
      {
        name: 'weather-assiant',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: weatherData
      },
      {
        name: 'ipLocation',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: ipData
      },
      {
        name: 'texttopicture',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: ttopData
      },
      {
        name: 'picturetotext',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: ptotData
      },
 {
        name: '翻译',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data:  translationData
      },
 {
        name: '智慧语音',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: soundData
      },
    ]
  };
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center',
      left: '85%'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
          fontSize: 20
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData.sort(function (a, b) {
    return a.value - b.value;
  }),
      },
    ]

  };
  return (
    <PageContainer
      content={<p style={{fontSize: '24px',fontWeight:'bold'}}>这是您的接口监控界面</p>}
    >
      <Card style={{
        width: '100%',
        marginBottom: 10,
        animation: `${fadeIn} 0.5s ease-in-out`
      }}>
      <p style={{ fontSize: '24px',fontWeight:'bold',textAlign:'center',marginRight:'4%'}}>接口调用次数饼状图</p>
      <ReactECharts loadingOption={{ showLoading: loading }} option={option} />
      </Card>
      <Card style={{
        width: '100%',
        animation: `${fadeIn} 0.5s ease-in-out`
      }}>
        <p style={{ fontSize: '24px',fontWeight:'bold',textAlign:'center',marginRight:'5%'}}>调用次数（周）</p>
        <Tabs
          animated={true}
          defaultActiveKey="2"
          items={[LineChartOutlined, BarChartOutlined].map((Icon, i) => {
            const id = String(i + 1);
            return {
              key: id,
              label: i===1?'柱状图':'折线图',
              children: i === 0 ? <ReactECharts loadingOption={{ showLoading: loading }} option={Weekoption} /> : <ReactECharts loadingOption={{ showLoading: loading }} option={WeekColoption} />,
            icon: <Icon />,
            };
          })}
        />
      </Card>
    </PageContainer>
  );
};

export default Admin;
